//
//  CJComposeView.swift
//  SinaWeibo
//
//  Created by 程建 on 16/10/6.
//  Copyright © 2016年 itcast. All rights reserved.
//
//  选择撰写类型的视图

import UIKit
import pop

class CJComposeView: UIView {

    //懒加载 存放按钮的数组
    lazy var buttonArray = [CJComposeButton]()
    
    
    override init(frame: CGRect) {
        super.init(frame: UIScreen.main.bounds)
        
        self.backgroundColor = UIColor.red
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //使用属性记录参数
    var targetVC: UIViewController?
    
    func show(target:UIViewController?) {
    
        self.targetVC = target
        
        //将自己添加到targetVC的根视图上
        target?.view.addSubview(self)
    }
    
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        
        for value in buttonArray.reversed().enumerated() {
            
            startAnimation(btn: value.element, index: value.offset, isUp: false)
            
        }
        
        //延迟执行
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.5) { 
             self.removeFromSuperview()
        }
        
       
    }
    
    //按钮从下面出来
    override func willMove(toSuperview newSuperview: UIView?) {
        super.willMove(toSuperview: newSuperview)
        
        //完成每个按钮的弹出动画
        //1.遍历所有的按钮
        for value in buttonArray.enumerated() {
        
           startAnimation(btn: value.element, index: value.offset)
        }
        
    }
    
    //执行动画
    private func startAnimation(btn:CJComposeButton,index:Int,isUp: Bool = true) {
        
        //实例化pop的弹簧动画执行对象
        let anim = POPSpringAnimation(propertyNamed: kPOPViewCenter)
        
        //设置动画执行的基本属性
        anim?.springBounciness = 10
        anim?.springSpeed = 12
        //设置动画时间
        anim?.beginTime = CACurrentMediaTime() + Double(index) * 0.025
        
        //设置toValue 结构体 应该包装成 NSValue
        //直接设置程序会崩溃
        anim?.toValue = NSValue.init(cgPoint: CGPoint(x: btn.center.x, y: btn.center.y + (isUp == true ? -350 : 350)))
        //添加到按钮上
        btn.pop_add(anim, forKey: nil)

        
    }
    
    
    //设置ui界面
    private func setupUI() {
        
        //截取当前屏幕
        //将图片设置为背景图片
        let backImagView = UIImageView(image: UIImage.snapShotCurrentScreen().applyLightEffect())
        
        //将截取的图片视图添加到视图上
        self.addSubview(backImagView)
        
        //添加图片
        let slogan = UIImageView(image: #imageLiteral(resourceName: "compose_slogan"))
        self.addSubview(slogan)
        
        //设置约束
        slogan.snp.makeConstraints { (make) in
            make.centerX.equalTo(self)
            make.top.equalTo(self).offset(100)
        }
        
        //添加微博类型的按钮
        addChildButtons()
    }
    
    private func addChildButtons() {
        
        
        let margin:CGFloat = (ScreenWidth - 3*composeBtnW) / (3+1)
        
        for i in 0..<6 {
            
            let btn = CJComposeButton()
            btn.setTitle("位置", for: .normal)
            btn.setImage(#imageLiteral(resourceName: "tabbar_compose_lbs"), for: .normal)
           
            //计算行和列
            //技术x和y
            let colIndex = i % 3
            let rowIndex = i / 3
            let btnX = margin + (margin+composeBtnW)*CGFloat(colIndex)
            let btnY = (margin + composeBtnH)*CGFloat(rowIndex) + ScreenHeight
            
            btn.frame = CGRect(x: btnX, y: btnY, width: composeBtnW, height: composeBtnH)
            btn.addTarget(self, action: #selector(composeTypeBtnDidClick(btn:)), for: .touchUpInside)
            self.addSubview(btn)
            
            //添加到数组当中
            buttonArray.append(btn)
            
        }
    }
    
    @objc private func composeTypeBtnDidClick(btn:CJComposeButton) {
        //1.对点击按钮执行放大操作
        //2.对没有点击的按钮执行缩小的操作
        UIView.animate(withDuration: 0.5, animations: { 
            //遍历按钮数组  用参数btn 和按钮中每一个元素作比较 ,如果相等就是被点击的按钮,否则就是其他按钮
            for composeBtn in self.buttonArray {
                composeBtn.alpha = 0.1
                if composeBtn == btn {
                    //执行放大效果
                    composeBtn.transform = CGAffineTransform.init(scaleX: 2, y: 2)
                }else {
                    //执行缩小
                    composeBtn.transform = CGAffineTransform.init(scaleX: 0.1, y: 0.1)
                }
            }
            
            }) { (_) in
                //跳转界面  如果交给服务器配置  就只能够获取到控制器名称的字符串
                //1.从数据中解析需要跳转的控制器的类名(字符串)
                let produceName = Bundle.main.infoDictionary!["CFBundleName"] as! String
                let className = produceName + "." + "CJComposeViewController"
                //2.根据字符串获取类型
                let type = NSClassFromString(className) as! UIViewController.Type
                //3.根据类型,实例化对象
                let vc = type.init()
                let nav = UINavigationController(rootViewController: vc)
                //4.跳转到目标控制器
                //2.页面跳转结束之后应该移除当前视图
                self.targetVC?.present(nav, animated: true, completion: {
                    self.removeFromSuperview()
                })
                
        }
        
        
    }
    
}
